import axios from 'axios'
import config from '../config/index'
import router from '../router/index'
import { ElMessage } from 'element-plus'

const NETWORK_ERROR = '网络异常，请稍后重试'
const TOKEN_INVALID = 'Token认证失败，请重新登录'

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 8000
})

service.interceptors.request.use(req => {
    const headers = req.headers
    if (!headers.Authorization) {
        headers.Authorization = 'Bearer Jack'
    }
    return req
})

service.interceptors.response.use(resp => {
    const { code, msg, data } = resp.data
    if (code === 200) {
        return data
    } else if (code === 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 15000);
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
})

function request(options) {
    options.methods = options.methods || 'get'
    if (options.methods.toLowerCase() === 'get') {
        options.params = options.data
    }

    if (config.env === 'prod') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return service(options)
}

export default request